package com.cy.milktea.pojo.System;


import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Redis implements InitializingBean {


    public static final String SHIRO_SESSION_PREFIX = "shiroSession:";  //------>shiro的session前缀,用于储存user

    public static final String ROLE_PREFIX = "rolePermission:";  //------------->角色权限列表
    public static final String IP_LIMIT_PREFIX = "ipLimit:";  //---------------->对每个ip访问设置60秒只能有200次访问

    public static final String QUEUING_ORDERS = "queuingOrderMap";  //---------->存储排队中的订单,用redis的map存储
    public static final String ORDER_QUEUE_VALUE = "orderQueueValue";  //------->每次完成一个订单减一,用于计算当前排队位置
    public static final String ORDER_QUEUE_LOCK = "orderQueueAtomicLock";  //--->锁: 用于保证map操作和value操作原子性

    public static final String ORDER_SORT_VALUE = "orderSortValue";  //--------->排队号生成key

    public static final String ORDER_ID_LIST = "orderIDList";  //--------------->订单流水号集合key
    public static final String ORDER_ID_INDEX = "orderIDIndex";  //------------->订单流水号索引key

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void afterPropertiesSet() {
        //存入订单流水号
        orderIDListToRedis();
        //存入流水号索引值
        orderIDIndexToRedis();
        //存入订单排序值
        orderSortValueToRedis();
        //初始化OrderQueueValue
        initOrderQueueValue();
    }

    private void orderIDListToRedis() {
        if (!redisTemplate.hasKey(Redis.ORDER_ID_LIST)) {
            List<String> list = new ArrayList<>();
            String str;
            int time;
            for (int i = 0; i < 100000; i++) {
                str = String.valueOf(i);
                time = 5 - str.length();
                for (int j = 0; j < time; j++) {
                    str = '0' + str;
                }
                list.add(str);
            }
            //乱序
            Collections.shuffle(list);
            redisTemplate.opsForList().rightPushAll(Redis.ORDER_ID_LIST, list);
        }
    }

    private void orderIDIndexToRedis() {
        if (!redisTemplate.hasKey(Redis.ORDER_ID_INDEX)) {
            redisTemplate.opsForValue().set(Redis.ORDER_ID_INDEX, -1);
        }
    }

    private void orderSortValueToRedis() {
        if (!redisTemplate.hasKey(Redis.ORDER_SORT_VALUE)) {
            redisTemplate.opsForValue().set(Redis.ORDER_SORT_VALUE, -1);
        }
    }

    private void initOrderQueueValue() {
        if (!redisTemplate.hasKey(Redis.ORDER_QUEUE_VALUE)) {
            redisTemplate.opsForValue().set(Redis.ORDER_QUEUE_VALUE, 0);
        }
    }
}
















